package com.github.postsanf.yinian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.OrderListItemAdapter;
import com.github.postsanf.yinian.bean.YNOrder;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNOrderResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class OrderListActivity extends BaseActivity implements View.OnClickListener {
    private ExpandableListView ex_orderlist_list;              // 列表视图
    private OrderListItemAdapter mAdapter;
    private int userId;
    private List<YNOrder> ynOrderList = new ArrayList<>();
    private final String redPacketUrl = "http://wx.zhuiyinanian.com/shop/coupon/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orderlist);
        initView();
        initOrderList();
    }

    private void initView() {
        userId = application.getCurID();
        findViewById(R.id.orderlist_back).setOnClickListener(this);
        findViewById(R.id.orderlist_help).setOnClickListener(this);
        ex_orderlist_list = ((ExpandableListView) findViewById(R.id.ex_orderlist_list));
        ex_orderlist_list.setGroupIndicator(null);
        mAdapter = new OrderListItemAdapter(OrderListActivity.this, ynOrderList, userId);
        ex_orderlist_list.setAdapter(mAdapter);
        if (getIntent() != null) {
            String ebOrderID = getIntent().getStringExtra("ebOrderID");
            if (!StringUtils.isEmpty(ebOrderID)) {
                initRedPacket(ebOrderID);
            }
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.orderlist_back:
                finish();
                break;
            case R.id.orderlist_help:
                break;
        }
    }

    private void initOrderList() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynShowOrderList))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNOrderResponse resOrder = gson.fromJson(s, YNOrderResponse.class);
                        if (ReqUtils.isSuccess(resOrder.getCode())) {
                            ynOrderList.addAll(resOrder.getData());
                            mAdapter.notifyDataSetChanged();
                            for (int i = 0; i < ynOrderList.size(); i++) {
                                Log.d("yuhao", "i=" + i);
                                ex_orderlist_list.expandGroup(i);
                            }
//                            Log.d("yuhao", "onSuccess="+resOrder.getData().get(0).getEbOrderNumber());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);

//        YNOrderResponse resOrder = gson.fromJson(s, YNOrderResponse.class);
    }

    private void initRedPacket(String ebOrderID) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("ebOrderID", ebOrderID);
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynCreateShareRedPacket))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject resultOrder = new JSONObject(s.toString());
                            if (ReqUtils.isSuccess(resultOrder.optString("code"))) {
                                String redPacketID = resultOrder.optJSONArray("data").optJSONObject(0).optString("redPacketID");
                                initDialog(redPacketID);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void initDialog(final String redPacketID) {
//        final Dialog canceldialog = new Dialog(this, R.style.dialog_remain_gift);
//        final View cancelView = getLayoutInflater().inflate(R.layout.yn_shop_redpacket_tip, null);
//        cancelView.findViewById(R.id.redpacket_tip_no).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                canceldialog.dismiss();
//            }
//        });
//        cancelView.findViewById(R.id.redpacket_tip_yes).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(OrderListActivity.this, TodayShareActivityRedpacket.class);
//                intent.putExtra("url", redPacketUrl + redPacketID);
//                startActivity(intent);
//                canceldialog.dismiss();
//
//            }
//        });
//        canceldialog.setContentView(cancelView);
//        canceldialog.show();
        Intent intent = new Intent(OrderListActivity.this, RedPacketDialogActivity.class);
        intent.putExtra("url", redPacketUrl + redPacketID);
        startActivity(intent);
    }

    private long fristTime;

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "orderList_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }
}
